<%@ page language="java" contentType="text/xml; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.util.*" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="com.mobilottery.server.*" %>
<%@ page import="com.mobilottery.server.UserManager"%>
<%@ page import="com.mobilottery.Constants"%>
<%@ page import="org.apache.log4j.Logger"%>
<%! private static Logger logger = Logger.getLogger("wsclient.jsp"); %>
<%! 
static Map<String, String> getQueryMap(String query)
	{
					
		String[] params = query.split("&");
		Map<String, String> map = new HashMap<String, String>();
		for (String param : params)
		{
			String name = param.split("=")[0];
			String value = param.split("=")[1];
			map.put(name, value);
		}
		return map;
	}
static public class DateUtils {
	  public static final String DATE_FORMAT_NOW = "dd/MM/yyyy HH:mm";

	  public static String now() {
	    Calendar cal = Calendar.getInstance();
	    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
	    return sdf.format(cal.getTime());

	  }
	  
	  public static Date Date() {
		    Calendar cal = Calendar.getInstance();
		    return cal.getTime();
		    
		  }
}
static public String checkLogin(String userid, String pass)
{
	//check if the user has logged in
	if(!UserManager.getInstance().isLoginMatch(userid, pass))
	{
		return Constants.RESULT_USER_DOESNT_EXISTS;
	}
	else
	{
		return Constants.RESULT_OK;
	}
	
}
public List<String> DoOperationLogin(String userid, String pass)
{
	String opStat = "";
	String result = "";
		
	//check if the user has logged in
	if(UserManager.getInstance().isLoginMatch(userid, pass))
	{
		opStat = "1";
		result = "<login_date>"+DateUtils.now() +"</login_date>";

		logger.debug("successful login");		
	}
	else
	{
		opStat = "0";		
		result = "User is not registred in out system - please register";		

		logger.debug("login failed");
	}
	return Arrays.asList(opStat,result);
	
}
public List<String> DoOperationMyGames(String userid, String pass)
{
	String opStat = "";
	String result = "";
	
	if(checkLogin(userid,pass) != Constants.RESULT_OK)
	{
		opStat = "0";
		
		result = "the user is not logged in - aborting";

		return Arrays.asList(opStat,result);
	}
	User user =  UserManager.getInstance().getUser(userid);
	
	//now get games according to userid
	List<GameParticipation> myGames ;
	try
	{
		myGames = GameProvider.getInstance().getGameManager().getUserActiveParticipations(user.getId());
	}
	catch(RuntimeException ex)
	{
		opStat = "0";
		
		result= "the system didn't find games you have participated in the past";

		logger.debug("get mygames error - "+ ex.getMessage());		

		return Arrays.asList(opStat, result);
		
	}
				
	//format the list to xml
	//start with tag games
	result = ("<games>\n");
	
	for (GameParticipation gameParticipation :  myGames)
	{
		Game game = gameParticipation.getGame();
		String winningNumbers = game.getWinningNumbersRaw();
		
		result = result.concat("<g>");
		result = result.concat("id='" + String.valueOf(game.getId()) + "'\n");
		result = result.concat("date='" + String.valueOf(gameParticipation.getParticipationDate()) + "'\n");
		result = result.concat("trns_id='" + String.valueOf(gameParticipation.getTransactionId()) + "'\n");
		result = result.concat("participation_info='" + String.valueOf(gameParticipation.getGuessedNumbersRaw() +"'"));
		if (game.isGameFinished())result = result.concat("\nwin_results='"+ game.getWinningNumbersRaw()+ "'" );
		if (game.isGameFinished())result = result.concat("\nuser_win_price='" + String.valueOf(gameParticipation.getWinningAmount()) + "'");
		result = result.concat(">Lotto</g>");
	}
	
	result = result.concat("</games>");
	
	opStat = "1";

	logger.debug("mygames operation completed successfuly");	
	
	return Arrays.asList(opStat,result);
	
}
public List<String> DoOperationNewGame(String userid, String pass)
{
	String opStat = "";
	String result = "";
	
	//check if user is valid
	//check if the user has logged in
	if(checkLogin(userid,pass) != Constants.RESULT_OK)
	{
		opStat = "0";
		
		result = "the user is not logged in - aborting";

		return Arrays.asList(opStat,result);
	}

	
	//now get games according to userid
	List<Game> gameList ;
	try
	{
		gameList = GameProvider.getInstance().getGameManager().getActiveGames();
	}
	catch(RuntimeException ex)
	{
		opStat = "0";
		
		result= "the system didn't find active games";

		logger.debug("get active games error - "+ ex.getMessage());		

		return Arrays.asList(opStat, result);
		
	}
	
	//format the list to xml
	result = ("<games>\n");
	
	for (Game game :  gameList)
	{
		result = result.concat("<g ");
		result = result.concat("id='" + String.valueOf(game.getId()) + "' ");
		result = result.concat("win_price='" + String.valueOf(game.getMaxPrize()) + "'>");
		result = result.concat("Lotto");
		result = result.concat("</g>\n");		
	}
	
	result = result.concat("</games>\n");
	
	opStat = "1";

	logger.debug("get list of active games completed successfuly");	
	
	return Arrays.asList(opStat,result);
	
}
public List<String> DoOperationParticipateGame(String userid, String pass, String gameid, String participation_info )
{
	String opStat = "";
	String result = "";
	
	//check if the user has logged in
	if(checkLogin(userid,pass) != Constants.RESULT_OK)
	{
		opStat = "0";
		
		result = "the user is not logged in - aborting";

		return Arrays.asList(opStat,result);
	}
	User user =  UserManager.getInstance().getUser(userid);
	
	//Get Game using GameId
	Game game;
	try
	{
		game = GameProvider.getInstance().getGameManager().getGame(Long.decode(gameid));
	}
	catch(RuntimeException ex)
	{
		opStat = "0";
		
		result = "the game is closed game id-" + gameid;

		logger.debug("get game error - "+ ex.getMessage());
				
		return Arrays.asList(opStat,result);
		
	}
	//make a list of the participation info
	String[] sNumbers = participation_info.split("_");
	
	List<Long> lNumbers =  new ArrayList<Long>(sNumbers.length);
	
	for (String num : sNumbers)
	{
		lNumbers.add(Long.decode(num));
	}
	
	String numRaw = "";
	
	for (String num: sNumbers)
	{
		numRaw = numRaw + num;
	}
	
	Long transactionId ;
		
	//create a game participation class and set all parameters
	GameParticipation gameParticipator = new GameParticipation(game,user, new Date(), lNumbers );
	
	try
	{
		transactionId = GameProvider.getInstance().addGameParticipation(gameParticipator);
	}
	catch(Exception ex)
	{
		opStat = "0";
		
		result = "an error had occured when trying to register to the required game - please try again later";

		logger.debug("adding user participation error - "+ ex.getMessage());
				
		return Arrays.asList(opStat,result);
		
	}
	
	opStat = "1";
	
	//return transction id
	result = "<trns_id>" + transactionId.toString() + "</trns_id>\n";			
	
	return Arrays.asList(opStat,result);
	
}
%>
<%	String opStat = ""; 
	String result = null;
	//parse incoming query string 
	Map<String, String> QueryMap = getQueryMap(request.getQueryString());
	//extract the operation from the map key
	String operation = QueryMap.get("operation");
	
	logger.debug("received operation " + operation);
 	//switch according to the operation and extract other data based on the operation id
	if 		("login".equals(operation))
	{
		List<String> ret = DoOperationLogin(QueryMap.get("userid"), QueryMap.get("pass"));
		opStat = ret.get(0);
		result = ret.get(1);
		
	}
	else if ("mygames".contains(operation))
	{
		List<String> ret = DoOperationMyGames(QueryMap.get("userid"), QueryMap.get("pass"));
		opStat = ret.get(0);
		result = ret.get(1);
	}
	else if ("newgame".equals(operation))
	{
		List<String> ret = DoOperationNewGame(QueryMap.get("userid"), QueryMap.get("pass"));
		opStat = ret.get(0);
		result = ret.get(1);
	}
	else if ("participate".equals(operation))
	{
		List<String> ret = DoOperationParticipateGame(QueryMap.get("userid"), QueryMap.get("pass"), QueryMap.get("gameid"), QueryMap.get("participation_info"));
		opStat = ret.get(0);
		result = ret.get(1);
	}
	else
	{
		opStat = "0";
		result = "No Such Operation";
		
	}
	logger.debug("returning opStat " + opStat + "result " + result);
	
%>
<root><status><%= opStat %></status><% 
if (opStat == "1")
	{
	%><status_desc>OK</status_desc><%= result %><%	
	}
	else
	{%><status_desc><%= result %></status_desc><%
	}%>
</root>